<template>
  <el-dialog v-model="visible" title="人员选择" width="800">
    <el-row justify="center">
      <el-col :span="10">
        <div class="mb-10">
          <el-input v-model="searchVal" size="small" clearable @input="onSearchChange" />
        </div>
        <div class="mb-10" v-if="result.length === 0">
          <el-button type="primary" size="small" @click="checkAll">全选</el-button>
          <EmoList ref="listRef1" :data="listData" :check-list="checkList" @check-change="handleSelectionChange" />
        </div>
        <div class="mb-10" v-else>
          <EmoList ref="listRef2" :data="result" :check-list="checkList" @check-change="handleSelectionChange" />
        </div>
        <div class="mb-10">
          <template v-if="result.length === 0">
            <EmoTree
              ref="departmentTreeRef"
              :data="departmentList"
              :check-list="checkList"
              :default-expanded-keys="['1799027080046813201']"
              @check-change="handleNodeChange"
            />
          </template>
          <template v-else>
            <EmoTree
              ref="groupTreeRef"
              :data="groupList"
              :check-list="checkList"
              :default-expanded-keys="['1799027160124465522']"
              @check-change="handleNodeChange"
            />
          </template>
        </div>
      </el-col>
      <el-col :span="14">
        <div class="mb-10">
          <el-button type="primary" size="small" @click="clearSelection">清空</el-button>
        </div>
        <div class="flex">
          <el-tag
            class="gap-2"
            v-for="tag in checkList"
            :key="tag"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag.name }}
          </el-tag>
        </div>
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, ref, computed } from "vue";
import { ElMessage } from "element-plus";
import { EmoTree, EmoList } from "../../checkbox";
import departmentData from "./department.json";
import userData from "./user.json";
import groupData from "./group.json";
import { transformArray } from "@/utils";

const departmentList = transformArray(departmentData, (item) => ({
  id: item.id,
  name: item.name || item.departmentName,
  type: item.type
}));

const listData = transformArray(userData, (item) => ({
  id: item.ownerId,
  name: item.aliasName
}));

const groupList = transformArray(groupData, (item) => ({
  id: item.id,
  name: item.name,
  type: item.orgData.type
}));

const props = defineProps<{
  modelValue: boolean;
}>();

const emit = defineEmits(["update:modelValue"]);

const visible = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

const searchVal = ref("");
const result = ref([]);
const checkList = ref([]);

const listRef1 = ref(null);
const listRef2 = ref(null);
const departmentTreeRef = ref(null);
const groupTreeRef = ref(null);

const handleCancel = () => {
  emit("update:modelValue", false);
};

const handleOk = () => {
  if (checkList.value.length === 0) {
    ElMessage.warning("请选择人员");
    return;
  }
  emit("update:modelValue", false);
  console.table(checkList.value);
};

const setCheckedList = (list: Recordable[]) => {
  checkList.value = list;
  departmentTreeRef.value?.setCheckedKeys(list);
  groupTreeRef.value?.setCheckedKeys(list);
  listRef1.value?.setCheckedRows(list);
  listRef2.value?.setCheckedRows(list);
};

const handleClose = (tag: Recordable) => {
  const newUserList = checkList.value.filter((m) => m.id !== tag.id);
  setCheckedList(newUserList);
};

const clearSelection = () => {
  setCheckedList([]);
};

const onSearchChange = (str: string) => {
  if (!str) {
    result.value = [];
    nextTick(() => {
      listRef1.value?.setCheckedRows(checkList.value);
      departmentTreeRef.value?.setCheckedKeys(checkList.value);
    });
  } else {
    const newList = listData.filter((item) => item.name.indexOf(str) > -1);
    result.value = newList;

    if (newList.length) {
      nextTick(() => {
        listRef2.value?.setCheckedRows(checkList.value);
        groupTreeRef.value?.setCheckedKeys(checkList.value);
      });
    }
  }
};

const handleSelectionChange = (row: Recordable) => {
  /** 是否已选中需移除 */
  const selectedIdx = checkList.value.findIndex((item) => !row.checked && item.id === row.id);
  if (selectedIdx > -1) {
    checkList.value.splice(selectedIdx, 1);
  } else {
    checkList.value.push(row);
  }
  departmentTreeRef.value?.setCheckedKeys(checkList.value);
  groupTreeRef.value?.setCheckedKeys(checkList.value);
};

const handleNodeChange = (rows) => {
  checkList.value = rows;
  listRef1.value?.setCheckedRows(rows);
  listRef2.value?.setCheckedRows(rows);
};

const checkAll = () => {
  checkList.value = listData;
  departmentTreeRef.value?.setCheckedKeys(listData);
  listRef1.value?.setCheckedRows(listData);
};
</script>

<style scoped>
.mb-10 {
  margin-bottom: 10px;
}

.flex {
  padding: 0 10px;
  display: flex;
  flex-wrap: wrap;
}

.gap-2 {
  margin: 4px;
}
</style>
